package controller

import (
	"crypto/md5"
	"fmt"
	"io"
	"log"
	"math"
	"md52phone/config"
	"md52phone/global"
	"sync"
	"time"

	"github.com/panjf2000/ants/v2"
)

type TaskData struct {
	key   []byte
	value string
	wg    *sync.WaitGroup
}

func InitMd5Data() {
	log.Println(">>>写入数据")
	start := time.Now().Unix()

	var swg sync.WaitGroup
	pool, _ := ants.NewPoolWithFunc(config.Conf.Rocks.ThreadNum, writeTask)
	defer pool.Release()

	hds := config.Conf.Rocks.Hd
	for _, hd := range hds {
		length := len(fmt.Sprintf("%d", hd))
		start := hd * int(math.Pow10(11-length))
		end := (hd + 1) * int(math.Pow10(11-length))
		log.Printf("写入数据：%v ~ %v \n", start, end)
		for i := start; i < end; i++ {
			swg.Add(1)
			if i%100000 == 0 {
				log.Printf("已写入10000条数据：%v", i)
			}
			value := fmt.Sprintf("%d", i)
			pool.Invoke(&TaskData{
				key:   getMD5(value),
				value: value,
				wg:    &swg,
			})
		}
	}
	swg.Wait()
	log.Printf("<<<耗时：%v", time.Now().Unix()-start)
}

func writeTask(data any) {
	taskData := data.(*TaskData)
	global.Service.Write(taskData.key, []byte(taskData.value))
	taskData.wg.Done()
}

func getMD5(key string) []byte {
	h := md5.New()
	io.WriteString(h, key)
	return h.Sum(nil)
}
